<!DOCTYPE html>
<html lang="en">

<head>
    <title>骑手必经点撒点</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="./utils/fengmap.map-license.min.js"></script>
    <script src="./utils/fengmap.plugin.draw.min.js"></script>
    <script src="./utils/fengmap.plugin.ui.min.js"></script>
    <script src="./utils/fengmap.plugin.fusion.min.js"></script>
    <script src="./utils/jquery-3.6.1.min.js"></script>
    <link rel="stylesheet" href="./css/layui.css">
    <link rel="stylesheet" href="./css/index.css">
    <link rel="stylesheet" href="./css/iconfont.css">
    <link rel="stylesheet" href="./css/toolBarStyle.css" />
    <link rel="stylesheet" href="./css/mapEditorNew.css">
    <style>
        .toolBarDiv {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .fm-control-groups {
            right: 20px !important;
        }

        .top-right {
            margin-right: 20px;
        }
    </style>
</head>

<body>
    <div class="toolBarDiv">
        <div class="control1">
            <button id="addPoint" type="button" class="layui-btn" onclick="drawOpetion('addPoint')">
                <i class="iconfont icon-dian"></i>
            </button>
            <!-- <button id="addLine" type="button" class="layui-btn" onclick="drawOpetion('addLine')">
                <i class="iconfont icon-xian"></i>
            </button> -->
            <button id="edit" type="button" class="layui-btn" onclick="drawOpetion('edit')">
                <i class="iconfont icon-huizhi"></i>
            </button>
            <button id="delete" type="button" class="layui-btn layui-btn-disabled" onclick="drawOpetion('delete')">
                <i class="iconfont icon-shanchu"></i>
            </button>
        </div>

        <div class="top-right">
            <button id="delete" type="button" class="layui-btn" onclick="redraw()">
                刷新
            </button>
            <!-- <button id="delete" type="button" class="layui-btn layui-btn-primary" onclick="save()">
                保存新增
            </button> -->
        </div>
    </div>
    <!-- <div class="tip">
        <p>
            <img src="https://developer.fengmap.com/fmAPI/images/tip.png" />请选择左侧工具绘制marker或对已有marker进行选中、移动、修改形状、删除等的编辑。
        </p>
        <p style="margin-left: 23px;">编辑状态下点击边线上的虚拟中点“小白点”可增加节点；选中任一节点点击“删除”图标可删除选中的节点。</p>
        <p style="margin-left: 23px;">注：虚拟中点无法删除。</p>
    </div> -->
    <div id="fengmap"></div>
</body>
<script>
    var $parent_this;
    var polygonAreas = [];
    var polygonOptions = [];

    var map;
    var mapdraw; // 绘制类
    var activeBtn; // 当前选中btn
    var markerList;
    var dbx = 'addRectangle';
    var dbxicon = 'icon-juxing';
    var subs = ['addRectangle', 'addPolygon', 'addCircle', 'addEllipse']; // 子菜单
    var historyAreaLevel = sessionStorage.getItem("O2O_AreaLevel") || 6;
    var options = {
        container: document.getElementById('fengmap'),
        appName: "商场导览端样例的导览端微程序",
        key: "36344769ec20478ffa7944380d45b217",
        mapID: '1813117783302119425',
        themeID: '1813128535299932162',
        license: "17a8f3db01aa030bf4f496d6d828c898",
        center: {
            x: 13559440.116626736,
            y: 3650453.950961055
        },
        level: parseInt(historyAreaLevel),
        mapZoom: 16,
        zoomRange: [10, 23],
        highlightPicker: [],                    // 取消触发高亮事件
        viewMode: fengmap.FMViewMode.MODE_2D,   // 2D视图模式
    }
    map = new fengmap.FMMap(options);
    map.on('loaded', function () {
        console.log('地图加载完成');
        initMapTapEvent();
        initFloorControl()
        // 初始化点线面编辑类
        initMapEditor();
        backView();
        $parent_this.iframeMapLoaded = true;
    })
    map.on('levelChanged', function (e) {
        sessionStorage.setItem("O2O_AreaLevel", e.level)
    })

    function latlngToMapXyCoords({ lat, lng }) {
        let mapCoords = fengmap.FMCalculator.latlngToMapCoordinate({
            x: Number(lng),
            y: Number(lat),
        });
        return mapCoords;
    }
    function mapXyToLatlngCoords({ x, y }) {
        let { x: lng, y: lat } = fengmap.FMCalculator.mapCoordinateToLatlng({
            x,
            y,
        });
        return {
            lng,
            lat,
        };
    }
    function initMapTapEvent() {
        /* 点击事件监听 */
        map.on('click', function (e) {

        });
    }
    // 初始化楼层导航器
    function initFloorControl() {
        floorInfos = map.getFloorInfos();
        var scrollFloorCtlOpt = {
            position: fengmap.FMControlPosition.RIGHT_TOP,
            floorButtonCount: 5,
            offset: {
                // x: -630,
                // y: 400
            },
            viewModeControl: true,
            floorModeControl: true,
            needAllLayerBtn: true,
        };
        scrollFloorControl = new fengmap.FMToolbar(scrollFloorCtlOpt);
        scrollFloorControl.addTo(map);
    }

    /* 初始化点线面编辑类 */
    function initMapEditor() {
        mapdraw = new fengmap.FMMarkerEditor(map);
        //设置点样式
        mapdraw.setStyle("pointStyle", {
            url: "./static/go-by-point.png", //图片url地址
            size: 32, //大小
            height: 3, //高度
            collision: false,
            anchor: fengmap.FMMarkerAnchor.CENTER
        });
        //设置线样式
        mapdraw.setStyle("lineStyle", {
            width: 2, //线的宽度
            type: fengmap.FMLineType.FULL, //线的类型
            color: '#2F79EE', //颜色
            height: 3 //高度
        });
        //设置面样式
        mapdraw.setStyle("polygonStyle", {
            color: '#8DB9FF', //颜色
            borderWidth: 2, //外框的宽度
            borderColor: '#2F79EE', //外框的颜色
            opacity: 0.5, //透明度
            height: 3 //高度
        });

        mapdraw.setStyle("centerStyle", { url: "https://developer.fengmap.com/fmAPI/images/edit-center.png", size: 20 });//设置中心标识图片地址
        mapdraw.setStyle("nodeStyle", {
            editStyle: {
                url: "https://developer.fengmap.com/fmAPI/images/pic-03.png",
                size: 12
            },
            newStyle: {
                url: "https://developer.fengmap.com/fmAPI/images/edit-node.png",
                size: 8,
            },
            selectedStyle: {
                url: "https://developer.fengmap.com/fmAPI/images/pic-03.png",
                size: 16,
            }
        })
        // mapdraw.setStyle("editStyle", { url: "https://developer.fengmap.com/fmAPI/images/edit-node.png", size: 10 });//设置顶点标识图片地址
        mapdraw.setStyle("pointRectColor", "#2F79EE");//设置点外包围框的颜色

        mapdraw.enable();//启用编辑工具
        // 绘制完成事件监听
        mapdraw.on("drawing", function (event) {
            console.log(event);
        });
        mapdraw.on("drawn", function (event) {
            console.log(event);
            getPoints(event)
        });
        mapdraw.on("deleted", function (event) {
            console.log("deleted", event);
            getPoints(event)
        });
        mapdraw.on("edited", function (event) {
            console.log("edited", event);
            getPoints(event)
        });
    }
    function getPoints(event) {
        console.log("event,-===>", event, mapdraw);
        let hasIndex = $parent_this.necPoints.findIndex(f => f.userID == event.target.userID);
        if (hasIndex == -1 && !event.target._timer) {
            event.target._timer = new Date().getTime()
        }
        if (hasIndex != -1) {
            mapdraw.markers.forEach((f, f_index) => {
                let hasIndex = $parent_this.necPoints.findIndex(ff => ff.userID == f.userID);
                if (hasIndex !== -1) {
                    f._timer = $parent_this.necPoints[hasIndex].timer
                }
            })
        }
        console.log("mapdraw _timer,-===>", mapdraw.markers.some(s => !s._timer));
        console.log("mapdraw.markers", mapdraw.markers.map(m => m.userID), $parent_this.necPoints.map(m => m.userID));

        let necPoints = mapdraw.markers.sort((a, b) => a._timer - b._timer).map((m, m_index) => {
            let coords = {
                x: m.x,
                y: m.y,
            }
            let latLng = mapXyToLatlngCoords(coords)
            m.url = `./static/go-by-point-${m_index}.png`;
            return {
                ...coords,
                ...latLng,
                level: m.level,
                floor: map.getFloor(m.level).name,
                timer: m._timer
            }
        })
        console.log(necPoints, mapdraw.markers.sort((a, b) => a._timer - b._timer));
        $parent_this.necPoints = necPoints
    }

    function redraw() {
        location.reload();
        $parent_this.reload()
    }
    function clearRecordData() {
        $parent_this.selectedArea = {};
    }
    /* 设置绘制类型 */
    function drawOpetion(type, icon) {
        // 清空选中
        if (activeBtn) {
            var activeDom = document.getElementById(activeBtn);
            activeDom.classList.remove('active');
            if (subs.indexOf(activeBtn) > -1) {
                var dom = document.getElementById('mian');
                dom.classList.remove('active');
            }
        }
        //再次点击取消
        if (type === activeBtn && type !== 'delete') {
            mapdraw.operationType = null;
            return;
        }
        if (type === 'dbx') {
            type = dbx;
            icon = dbxicon;
        };

        if (type === 'delete') {
            currentHandlePolygon = {
                _type: 'delete'
            }
            console.log(markerList);
            mapdraw.delete(markerList)

        } else {
            // 设置类型
            mapdraw.operationType = type;
        }
        if (mapdraw.operationType === 'edit') {
            $('#delete').removeAttr('disabled')
            $('#delete').removeClass('layui-btn-disabled');
            var dom = document.getElementById("edit");
            dom.classList.add('active');
        } else {
            $('#delete').attr('disabled', true)
            $('#delete').addClass('layui-btn-disabled');
            var dom = document.getElementById("edit");
            dom.classList.remove('active');
        }

        //更新选中
        if (subs.indexOf(type) > -1) {
            var dom1 = document.getElementById('dbx');
            dom1.classList.remove(dbxicon);
            dbx = type;
            dbxicon = icon;
            var dom = document.getElementById('mian');
            dom.classList.add('active');
            dom1.classList.add(dbxicon);
            clearRecordData();
        }
        if (type != "delete") {
            var dom = document.getElementById(type);
            dom.classList.add('active');
        }
        activeBtn = type;
    }

    var polygons = [];            // 不规则多边形对象

    function backView() {
        $parent_this.$http.get($parent_this.$http.adornUrl("/platform/essential/airportAreaList"))
            .then(result => {
                console.log($parent_this.dataForm);
                polygonAreas = result.data.filter(f => f.id == $parent_this.dataForm.fromId || f.id == $parent_this.dataForm.toId).map(m => {
                    let pointRestrict = isJsonString(m.pointRestrict) ? JSON.parse(m.pointRestrict) : [];
                    m.airportStation = isJsonString(m.airportStation) ? JSON.parse(m.airportStation) : m.airportStation;
                    pointRestrict.forEach(f => {
                        f.parent = { airportStation: m.airportStation, floor: m.floor, id: m.id };
                    });
                    return { ...m, pointRestrict };
                });
                if ($parent_this.dataForm.id && $parent_this.necPoints && $parent_this.necPoints.length) {
                    $parent_this.necPoints.forEach((f, f_index) => {
                        let imageOption = {
                            markerType: fengmap.FMType.IMAGE_MARKER,
                            x: f.x,
                            y: f.y,
                            url: `./static/go-by-point-${f_index}.png`, //图片url地址
                            size: 32,
                            height: 3, //高度
                            collision: true,
                            level: f.level,
                        }
                        mapdraw.add(imageOption);
                        if (f.timer) {
                            mapdraw.markers[f_index]._timer = f.timer;
                        }
                        f.userID = (mapdraw.markers.find(mf => mf.x == f.x && mf.y == f.y && mf.level == f.level)).userID
                    })
                    console.log(">>>>>>", mapdraw, $parent_this.necPoints);

                }
                //初始化面板设置参数
                let panelSet = {
                    height: 5,
                    opacity: 50,
                    color: '#2F79EE',
                    borderWidth: 2,
                    borderColor: '#8DB9FF',
                }
                polygonAreas.forEach((f, index) => {
                    let level = f.pointRestrict[0]?.level
                    let floor = map.getFloor(level);

                    let publicOption = {
                        ...panelSet,
                        opacity: Number(panelSet.opacity) / 100,
                    }
                    /* 添加任意多边形 */
                    let polygonOption = {
                        points: f.pointRestrict,
                        ...publicOption
                    }
                    polygons[index] = new fengmap.FMPolygonMarker(polygonOption);
                    polygons[index].addTo(floor);
                });
                mapCameraMove(polygonAreas[0])
                $('#delete').attr('disabled', true);
            });
    }


    function isJsonString(str) {
        try {
            if (typeof JSON.parse(str) == "object") {
                return true;
            }
        } catch (e) {
        }
        return false;
    }

    function disableEdit() { }


    function mapCameraMove(selectedArea) {
        let [coords] = selectedArea.pointRestrict
        map.setLevel({
            animate: true,
            level: coords.level,
            duration: 0.3,
            finish: () => {
                map.setCenter({
                    animate: true,
                    duration: 0.5,
                    x: coords.x,
                    y: coords.y,
                });
            },
        });
    }

</script>

</html>